package textEngine.searchInfo;


import java.io.UnsupportedEncodingException;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.ResultSetFormatter;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;

import domain.NIDInfoRecord;
import domain.RepresentationsNamesRecord;

import java.text.Normalizer;
import java.text.Normalizer.Form;

import javax.xml.ws.http.HTTPException;

import util.Utils;

public class DBpediaPersonFinder {
	
	
	public static void main(String[] args) {
		
		
		//Model model= ModelFactory.createDefaultModel();
		String service1 = "http://dbpedia.org/sparql";
		String service = "http://it.dbpedia.org/sparql";
        String queryString1 = "";
        queryString1 = "PREFIX foaf: <http://xmlns.com/foaf/0.1/>" +
        		//"PREFIX dbo: <http://dbpedia.org/ontology/>"+
        		//"PREFIX pf: <http://jena.hpl.hp.com/ARQ/property#>"+
        		//"PREFIX bif: <http://www.openlinksw.com/schema/sparql/extensions#>"+
        		"SELECT DISTINCT * WHERE {" +
        		"?instance a <http://dbpedia.org/ontology/Person> ;" +
        		"foaf:name ?label ." +
        		"?label <bif:contains> \"Rossi\" . " +
//        		"?label <bif:contains> \"Paolo\" . " +
        	//	"?instance <http://dbpedia.org/ontology/birthYear> ?birthYear."+
        		"FILTER (lang(?label) = 'en'). " +
        		//"?label pf:textMatch 'Andrea' ."+
        		
        	
        	
        		"?instance <http://dbpedia.org/ontology/thumbnail> ?thumb"+
        		
        		"}";
        
     String queryString = "";
         queryString= " SELECT * WHERE {"+
        	  "?instance a <http://dbpedia.org/ontology/Person> . "+
        	  "?instance <http://xmlns.com/foaf/0.1/name>       ?name . "+
        	  "?instance <http://xmlns.com/foaf/0.1/surname>       ?surname ." +
        	  "FILTER( str(?name) = \"Paolo\" ) ."+
        	  "FILTER(str(?surname) = \"Rossi\") ."+
        //	  "?instance <http://dbpedia.org/ontology/thumbnail> ?thumb"+
        	"}";
        
      /*  String s2 = "PREFIX  g:    <http://www.w3.org/2003/01/geo/wgs84_pos#>\n" +
                "PREFIX  rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n" +
                "PREFIX  onto: <http://dbpedia.org/ontology/>\n" +
                "\n" +
                "SELECT  ?subject ?stadium ?lat ?long\n" +
                "WHERE\n" +
                "  { ?subject g:lat ?lat .\n" +
                "    ?subject g:long ?long .\n" +
                "    ?subject <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> onto:Stadium .\n" +
                "    ?subject rdfs:label ?stadium\n" +
                "    FILTER ( ( ( ( ( ?lat >= 52.4814 ) && ( ?lat <= 57.4814 ) ) && ( ?long >= -1.89358 ) ) && ( ?long <= 3.10642 ) ) && ( lang(?stadium) = \"en\" ) )\n" +
                "  }\n" +
                "LIMIT   5\n" +
                "";
        */
        /*VirtGraph set = new VirtGraph (service, "dba", "dba");
		VirtuosoQueryExecution query =  VirtuosoQueryExecutionFactory.create(queryString,set);
		ResultSet results = query.execSelect();*/
        Query query= QueryFactory.create(queryString);
		//QueryEngineHTTP qexec = QueryExecutionFactory.createServiceRequest(service, query);
        QueryExecution qexec = QueryExecutionFactory.createServiceRequest(service, query);
		ResultSet results = qexec.execSelect();
		//System.out.write(ResultSetFormatter.asXMLString(results1, xslfile1).getBytes("UTF-8"));
		
		//ResultSetFormatter.out(System.out, results,  query) ;
		Iterator<String> it=results.getResultVars().iterator();
		while(it.hasNext()){
			System.out.println(it.next());
		}
		
		while ( results.hasNext() ) {
            QuerySolution soln = results.nextSolution();
            Resource region = soln.getResource("instance");
            System.out.println(region.getURI());
		}
		//System.out.println(results.next().get("label"));
		while(results.hasNext()){
			Model m=results.getResourceModel();
			//m.getProperty("label");
			m.write(System.out, "Turtle");
		}
		
		
		List<QuerySolution> list = ResultSetFormatter.toList(results); 
		Iterator<QuerySolution> it2= list.iterator();
		while(results.hasNext()){
		
			QuerySolution q = results.nextSolution();
			RDFNode node = q.get("thumb");
			System.out.println(node.toString());
		}
		while(it2.hasNext()){
			QuerySolution qs=it2.next();
			String labelTemp= qs.get("label").toString();
			String personTemp= qs.get("thumb").toString();
			try {
				String out2 = new String(labelTemp.getBytes("iso-8859-1"), "utf-8");
				String out3= new String(personTemp);
				System.out.println(out2);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		
	//	System.out.println(list.get(1).get("label"));
		qexec.close();
		
	}

	public List<NIDInfoRecord> getPersonDBpedia(List<RepresentationsNamesRecord> masterNameList, String infoType,int numeroMassimoRisultati, String serviceUrl) {
		

		String service = "http://dbpedia.org/sparql";
		if (serviceUrl!=null && !serviceUrl.equals("")) service= serviceUrl;
		System.out.println("Start searching "+masterNameList.size()+" people on DBpedia ("+service+")");
		
		ArrayList<NIDInfoRecord> infoList= new ArrayList<NIDInfoRecord>();
		
		int i=0;
		for(RepresentationsNamesRecord rep: masterNameList){
		//	util.Utils.printProgBar((int)(((float)i/masterNameList.size())*100));
		//	i++;
			System.out.print("\nLooking for "+rep.getValue()+" (NID:"+rep.getNID()+") on DBpedia...\n");
		
			
			ArrayList<String[]> combinazioniNameSurname= Util.nameSurnameCombination(rep.getValue());
			Boolean FoundSomething=false;
			if (combinazioniNameSurname!=null) {
				
				for (String[] nameSurname :combinazioniNameSurname ) {
					
					
					if (nameSurname!=null && nameSurname[0]!=null && nameSurname[1]!= null){ //controllo che la nameSurnameCombination() torni qualcosa
						
					
						String firstname=removeAccents(nameSurname[0]).replaceAll("[^a-zA-Z_]", "");
						String lastname=removeAccents(nameSurname[1]).replaceAll("[^a-zA-Z_]", "");
						if(!(firstname==null || firstname.equals("") || lastname==null || lastname.equals("")) ){
						String queryString = "";
				        queryString= " SELECT * WHERE {"+
				       	  "?instance a <http://dbpedia.org/ontology/Person> . "+
				       	  "?instance <http://xmlns.com/foaf/0.1/name>       ?name . "+
				       	  "?instance <http://xmlns.com/foaf/0.1/surname>       ?surname ." +
				       	   "?name <bif:contains> \""+firstname+"\" ."+
				           "?surname <bif:contains> \""+lastname+"\" ."+
				       	"}";
				     
				        
				        

				        QueryExecution qexec = QueryExecutionFactory.createServiceRequest(service, QueryFactory.create(queryString)); 
				       int timeout=300000;//300000;
				        qexec.setTimeout(timeout,timeout);
				        
				        try {
				        	 ResultSet results = qexec.execSelect();
				        	// if (results==null || results.hasNext()==false) System.out.print("\t("+firstname+" "+lastname+" not found!)\n");
				        	  while ( results.hasNext() ) {
						        	long data= new Date().getTime();
						            QuerySolution soln = results.nextSolution();
						            Resource instance=soln.getResource("instance");
						            //System.out.println(instance.getURI());
						            NIDInfoRecord nir= new NIDInfoRecord();
						            nir.setInfo(instance.getURI());
						            nir.setNID(rep.getNID());
						            nir.setTypeInfo(infoType);
						            nir.setDataLastInfoSearch(data);
						            infoList.add(nir);
						            FoundSomething=true;
						            System.out.println("\tFounded character for \""+firstname+"\" \""+lastname+"\" on DBpedia:"+nir.getInfo());
						            //System.out.flush();
						        }
						} catch (Exception e) {
							
							System.out.print("\t(Timeout expired for \""+firstname+"\" \""+lastname+"\".DBpedia has discarded the query(for DBpedia internal timeout) or DBpedia did not reply within the fixed "+timeout+"ms)\n");
							//System.err.println("\nHo avuto un problema con  "+ firstname + " "+ lastname +" su "+service );//.+"\n Errore: "+ e.getMessage());
							//System.out.flush();
						}			      
					  }
					}
				}
				
			}
			if (FoundSomething==false) System.out.print("\t ...nothing found!\n");
		
		}
		
		System.out.println( "\n\tComplete: "+infoList.size() + " DBpedia resource matched.\n");
		
		return infoList;
	}
	
	public static String removeAccents(String text) {
	    return text == null ? null
	        : Normalizer.normalize(text, Form.NFD)
	            .replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
	}
	
	
	

}